package com.lj.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lj.ucenter.entity.Member;
import com.lj.ucenter.entity.vo.LoginVo;
import com.lj.ucenter.entity.vo.RegisterVo;
import com.lj.ucenter.mapper.MemberMapper;
import com.lj.ucenter.service.MemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lj.utils.exception.APIException;
import com.lj.utils.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author luojing
 * @since 2021-06-30
 */
@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public String login(LoginVo loginVo) {
        //手机、密码判空
        if (StringUtils.isEmpty(loginVo.getMobile()) || StringUtils.isEmpty(loginVo.getPassword())) {
            throw new APIException("登录失败：手机号或密码不得为空");
        }

        //判断手机号是否存在
        Member mobile = this.getOne(new QueryWrapper<Member>().eq("mobile", loginVo.getMobile()));
        if (mobile == null) {
            throw new APIException("登录失败：手机号或密码不正确");
        }
        //判断密码是否正确
        if (!DigestUtils.md5DigestAsHex(loginVo.getPassword().getBytes(StandardCharsets.UTF_8))
                .equals(mobile.getPassword())) {
            throw new APIException("登录失败：手机号或密码不正确");
        }
        //判断是否被禁用
        if (mobile.getIsDisabled()) {
            throw new APIException("登录失败：该用户已被禁用");
        }

        return JwtUtils.getJwtToken(mobile.getId(), mobile.getNickname());
    }

    @Override
    public Boolean register(RegisterVo registerVo) {
        //校验手机号(邮箱)对应的验证码
        String redisCode = redisTemplate.opsForValue().get(registerVo.getMobile());
        if (!registerVo.getCode().equals(redisCode)) {
            throw new APIException("验证码错误！");
        }
        //判断该手机（邮箱）是否已存在
        int count = this.count(new QueryWrapper<Member>().eq("mobile", registerVo.getMobile()));
        if (count != 0) {
            throw new APIException("该账户已存在！");
        }
        //密码md5加密
        String password = DigestUtils.md5DigestAsHex(registerVo.getPassword().getBytes(StandardCharsets.UTF_8));
        //注册
        Member member = new Member();
        member.setMobile(registerVo.getMobile());
        member.setNickname(registerVo.getNickname());
        member.setPassword(password);
        return this.save(member);
    }
}
